package com.archstoday.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.archstoday.BaseApp;
import com.archstoday.R;
import com.archstoday.activity.MainActivity;
import com.archstoday.activity.TenderDetailsActivity;
import com.archstoday.adapter.MainTenderAdapter;
import com.archstoday.common.AsRes;
import com.archstoday.entity.ScreenEntity;
import com.archstoday.entity.TenderListEntity;
import com.archstoday.utils.ScreenUtils;
import com.archstoday.utils.ToolUtils;
import com.archstoday.view.PullToRefreshLayout;
import com.base.http.common.BaseHttpClient;
import com.base.utils.StringUtil;
import com.xw.repo.refresh.PullListView;

import java.util.HashMap;
import java.util.Map;

import static com.archstoday.R.id.screen_tip_one;
import static com.archstoday.R.id.screen_tip_three;
import static com.archstoday.R.id.screen_tip_two;

/**
 * 招投标列表页
 */
public class MainTenderFragment extends AsBaseFragment implements PullToRefreshLayout.OnRefreshListener {

    private TextView mAllTv, mScreenBtn;
    private PullToRefreshLayout mPullLayout;
    private PullListView mPullList;
    private LinearLayout mScreenView, mScreenLayout;
    private TextView mCancelBtn, mSubmitBtn;
    private ProgressBar mProgress;
    private LinearLayout mNoneLayout;
    private TextView mScreenTipOne, mScreenTipTwo, mScreenTipThree;

    private View mFootView;
    private String mSlipType;
    private MainTenderAdapter mAdapter;
    private ScreenEntity mScreenEntity;

    private boolean isFirst;
    private String mSince, mMax;
    private boolean isLoadMore;

    @Override
    protected View initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_list, null);
        mAllTv = (TextView) view.findViewById(R.id.main_all_tv);
        mScreenBtn = (TextView) view.findViewById(R.id.main_screen_btn);
        mPullLayout = (PullToRefreshLayout) view.findViewById(R.id.pull_layout);
        mPullList = (PullListView) view.findViewById(R.id.pull_list);
        mPullLayout.setOnRefreshListener(this);
        mScreenView = (LinearLayout) view.findViewById(R.id.screen_layout);
        mScreenLayout = (LinearLayout) view.findViewById(R.id.dialog_screen_layout);
        mCancelBtn = (TextView) view.findViewById(R.id.dialog_cancel_btn);
        mSubmitBtn = (TextView) view.findViewById(R.id.dialog_submit_btn);
        mProgress = (ProgressBar) view.findViewById(R.id.progress_bar);
        mNoneLayout = (LinearLayout) view.findViewById(R.id.search_none_layout);
        mScreenTipOne = (TextView) view.findViewById(screen_tip_one);
        mScreenTipTwo = (TextView) view.findViewById(screen_tip_two);
        mScreenTipThree = (TextView) view.findViewById(screen_tip_three);

        return view;
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        mAllTv.setVisibility(View.GONE);
        mFootView = LayoutInflater.from(mAct).inflate(R.layout.view_load_more, null);
        mSince = ToolUtils.getSince();
        mMax = ToolUtils.getSince();
        mAdapter = new MainTenderAdapter(mAct);
        mPullList.setAdapter(mAdapter);
        mSlipType = AsRes.REFRESH;
        isFirst = true;
        isLoadMore = false;
        upData();
    }

    public void onBack() {
        if (mScreenView.getVisibility() == View.VISIBLE) {
            mScreenView.setVisibility(View.GONE);
        } else {
            ((MainActivity) mAct).onBack();
        }
    }

    private void showScreen() {
        if (!StringUtil.isEmpty(ScreenUtils.getmScreenTypeValue())) {
            mScreenTipOne.setVisibility(View.VISIBLE);
            mScreenTipOne.setText(ScreenUtils.getmScreenTypeValue());
        } else {
            mScreenTipOne.setVisibility(View.GONE);
        }

        if (!StringUtil.isEmpty(ScreenUtils.getmScreenAreaValue())) {
            mScreenTipTwo.setVisibility(View.VISIBLE);
            mScreenTipTwo.setText(ScreenUtils.getmScreenAreaValue());
        } else {
            mScreenTipTwo.setVisibility(View.GONE);
        }

        if (!StringUtil.isEmpty(ScreenUtils.getmScreenStatusValue())) {
            mScreenTipThree.setVisibility(View.VISIBLE);
            mScreenTipThree.setText(ScreenUtils.getmScreenStatusValue());
        } else {
            mScreenTipThree.setVisibility(View.GONE);
        }
    }

    @Override
    protected void initListener() {
        mScreenBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getEvent(BaseApp.E_SCREEN, BaseApp.PGET_TYPE_TENDER_SCREEN);
                if (mScreenEntity == null) {
                    getScreen();
                } else {
                    ScreenUtils.addScreen(mAct, mScreenLayout, mScreenEntity);
                    mScreenView.setVisibility(View.VISIBLE);
                }
            }
        });

        mCancelBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mScreenView.setVisibility(View.GONE);
            }
        });

        mSubmitBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mPullList.setPullUpEnable(true);
                mPullList.removeFooterView(mFootView);
                isLoadMore = false;
                isFirst = true;
                mScreenView.setVisibility(View.GONE);
                mSince = ToolUtils.getSince();
                mMax = ToolUtils.getSince();
                mAdapter.setData(null);
                mAllTv.setText(StringUtil.replace(mAct.getString(R.string.main_tip_all),
                        "*", "0"));

                ScreenUtils.mScreenTypeBefor = ScreenUtils.getmScreenType();
                ScreenUtils.mScreenAreaBefor = ScreenUtils.getmScreenArea();
                ScreenUtils.mScreenStatusBefor = ScreenUtils.getmScreenStatus();

                if (StringUtil.isEmpty(ScreenUtils.getmScreenType())
                        && StringUtil.isEmpty(ScreenUtils.getmScreenArea())
                        && StringUtil.isEmpty(ScreenUtils.getmScreenStatus())) {
                    mScreenBtn.setSelected(false);
                } else {
                    mScreenBtn.setSelected(true);
                }
                showScreen();

                mSlipType = AsRes.REFRESH;
                upData();
            }
        });

        mPullList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (mAdapter.getItem(i) != null) {
                    Map<String, String> info = new HashMap<>();
                    info.put("articleId", String.valueOf(mAdapter.getItem(i).getId()));
//                    info.put("categoryId1", String.valueOf(mAdapter.getItem(i).))
                    getEvent(BaseApp.E_DETAILS, BaseApp.PAGE_TYPE_TENDER,
                            ToolUtils.mapToJson(info));

                    Intent intent = new Intent(mAct, TenderDetailsActivity.class);
                    intent.putExtra("id", mAdapter.getItem(i).getId());
                    intent.putExtra("title", mAdapter.getItem(i).getLrsStatus());
                    startActivity(intent);
                }
            }
        });
    }

    private void getScreen() {
        initParameter();
        mParams.put("selectType", "recruit");

        sendEncryptPostRequest(AsRes.getInstance().getUrl(AsRes.GET_SELECT_BASE),
                AsRes.GET_SELECT_BASE, mParams, ScreenEntity.class);
    }

    private void upData() {
        if (mAdapter.getCount() > 0) {
            mMax = mAdapter.getItem(0).getUpdateTime();
            mSince = mAdapter.getItem(mAdapter.getCount() - 1).getUpdateTime();
        }

        initParameter();
        mParams.put("pageSize", 20);
        mParams.put("slipType", mSlipType);
        mParams.put("since", mSince);
        mParams.put("max", mMax);
        mParams.put("range", 60);
        mParams.put("recruitOrgType", ScreenUtils.getmScreenType()); // 类型
        mParams.put("area", ScreenUtils.getmScreenArea());  // 地区
        mParams.put("lrsstatus", ScreenUtils.getmScreenStatus());  //状态

        sendEncryptPostRequest(AsRes.getInstance().getUrl(AsRes.GET_RECRUIT_LIST),
                AsRes.GET_RECRUIT_LIST, mParams, TenderListEntity.class);
    }

    @Override
    protected void onSuccess(String content, BaseHttpClient client, Object parse) {
        mProgress.setVisibility(View.GONE);
        mPullLayout.refreshFinish(true);
        mPullLayout.loadMoreFinish(true);
        if (client.getUrlIdentifier() == AsRes.GET_RECRUIT_LIST) {
            TenderListEntity entity = (TenderListEntity) parse;
            if (ToolUtils.isSuccess(entity.getStatus())) {
                if (entity.getData() != null && entity.getData().size() > 0) {
                    mNoneLayout.setVisibility(View.GONE);
                    if (mSlipType == AsRes.REFRESH) {
                        mAdapter.setData(entity.getData());
                    } else {
                        mAdapter.addData(entity.getData());
                    }
//                    mSince = entity.getData().get(0).getUpdateTime();
//                    mMax = entity.getData().get(entity.getData().size() - 1).getUpdateTime();
                } else {
                    if (mSlipType == AsRes.REFRESH) {
                        if (isFirst) {
                            mSlipType = AsRes.LOADMORE;
                            upData();
                        } else {
                            if (mAdapter.getCount() == 0) {
                                mNoneLayout.setVisibility(View.VISIBLE);
                                mPullList.setPullUpEnable(false);
                            }
                        }
                    } else {
                        if (isLoadMore) {
                            mNoneLayout.setVisibility(View.GONE);
                            mPullList.addFooterView(mFootView);
                            mPullList.setPullUpEnable(false);
                        } else {
                            mNoneLayout.setVisibility(View.VISIBLE);
                            mPullList.setPullUpEnable(false);
                        }
                    }
                }
                if (isFirst) {
                    isFirst = false;
                }
                mAllTv.setText(StringUtil.replace(mAct.getString(R.string.main_tip_all),
                        "*", String.valueOf(mAdapter.getCount())));
            } else {
                showToast(entity.getMsg());
            }
        } else if (client.getUrlIdentifier() == AsRes.GET_SELECT_BASE) {
            mScreenEntity = (ScreenEntity) parse;
            if (ToolUtils.isSuccess(mScreenEntity.getStatus())) {
                ScreenUtils.addScreen(mAct, mScreenLayout, mScreenEntity);
                mScreenView.setVisibility(View.VISIBLE);
            } else {
                showToast(mScreenEntity.getMsg());
            }
        }
    }

    @Override
    protected void onError(Throwable error, BaseHttpClient client) {
        new Thread() {
            @Override
            public void run() {
                new Handler(Looper.getMainLooper()).post(runnable);
            }
        }.start();
    }

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            mProgress.setVisibility(View.GONE);
            mPullLayout.refreshFinish(true);
            mPullLayout.loadMoreFinish(true);

            if (mAdapter.getCount() == 0) {
                mNoneLayout.setVisibility(View.VISIBLE);
                mPullList.setPullUpEnable(false);
            }

            showToast(R.string.intent_error);
        }
    };

    @Override
    public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
        mPullList.setPullUpEnable(true);
        mPullList.removeFooterView(mFootView);
        mSlipType = AsRes.REFRESH;
        upData();
    }

    @Override
    public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
        isLoadMore = true;
        mSlipType = AsRes.LOADMORE;
        upData();
    }


}